﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel.Composition;
using TweetStream.Extensions.Contracts;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using System.Net;

namespace TweetStream.Extensions.TwitPic
{
    [Export ( typeof(IThirdPartyContent))]
	public partial class InlineImage : UserControl, IThirdPartyContent
	{

        //public delegate void ShowImageUriHandler(object sender, IHLArgs args);
        //public delegate void ShowHtmlUriHandler(object sender, IHTMLArgs args);

        //public event ShowImageUriHandler ShowImageUri;
        //public event ShowHtmlUriHandler ShowHtmlUri;

		public InlineImage()
		{
			// Required to initialize variables
			InitializeComponent();
		}


        #region Source


        public ImageSource Source
        {
            get { return (ImageSource)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(ImageSource), typeof(InlineImage), new PropertyMetadata(SourceChanged));

        private static void SourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            ((InlineImage)obj).imgSource.Source = (ImageSource)args.NewValue;
        }
        #endregion


        void IThirdPartyContent.InitControl(InitMessage msg)
        {
            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
            //wc.OpenReadAsync(this.LinkUri);

            State st = new State()
            {
                DynamicControlsContainer = msg.DynamicControlsContainer,
                Url = msg.Url,
                Key = msg.Key,
                Uri = new Uri(msg.Url, UriKind.Absolute),
                LoadingAnimation = msg.LoadingAnimation,
                LoadingAnimationContainer = msg.LoadingAnimationContainer

            };
            wc.DownloadStringAsync(new Uri(msg.Url), st);
        }


        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            State st = (State)e.UserState;

            try
            {
                string res = e.Result;


                UserControl ctl = DoCheck(st.Key, res);

                if (ctl != null)
                {
                    string sType = ctl.GetType().Name;

                    if (sType.ToLower().Contains("image"))
                    {
                        //st.DynamicControlsContainer.Children.Add(ctl);
                        //if (ShowImageUri != null) ShowImageUri(ctl, new IHLArgs(st.DynamicControlsContainer));
                        ctl.UpdateLayout();
                        st.DynamicControlsContainer.Children.Clear();
                        st.DynamicControlsContainer.Children.Add(ctl);
                        st.DynamicControlsContainer.Visibility = Visibility.Visible;
                        st.DynamicControlsContainer.Height += (ctl).ActualHeight;
                        
                    }
                    else if (sType.ToLower().Contains("html"))
                    {
                        //st.DynamicControlsContainer.Children.Add(ctl);
                        //if (ShowHtmlUri != null) ShowHtmlUri(ctl, new IHTMLArgs(st.DynamicControlsContainer));
                        ctl.UpdateLayout();
                        st.DynamicControlsContainer.Children.Clear();
                        st.DynamicControlsContainer.Children.Add(ctl);
                        st.DynamicControlsContainer.Visibility = Visibility.Visible;
                        st.DynamicControlsContainer.Height += (ctl).ActualHeight;
                        
                    }


                }

                
            }
            catch { }
            finally
            {
                st.LoadingAnimation.Stop();
                st.LoadingAnimationContainer.Children.Clear();
            }

        }

        
        UserControl IThirdPartyContent.DoCheck(string key, string contentToParse)
        {
            return DoCheck(key, contentToParse);
        }


        private UserControl DoCheck(string key, string contentToParse)
        {
            
            if (key == "twitpic")
            {
                Match match = System.Text.RegularExpressions.Regex.Match(contentToParse, "<img id=\"photo-display\" class=\"photo-large\" src=\"http:\\/\\/([a-zA-Z0-9\\._\\'\\/\\-\\?\\=\\#\\&\\%]*)\"");
                if (match.Success)
                {
                    InlineImage ctl = new InlineImage()
                    {
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                        VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
                        Source = new BitmapImage(new Uri("http://" + match.Groups[1].Value, UriKind.RelativeOrAbsolute)),
                        Width = 200
                    };
                    return ctl;
                }

            }

            return null;
        }


        bool IThirdPartyContent.CheckIfAutoLoad(string key)
        {
            if (key == "twitpic") return true;

            return false;
        }



        public string RetrieveKey(string url)
        {
            
            if (url.ToLower().Contains("twitpic.com")) return "twitpic";
            else return string.Empty;
        }


    }

    public class State {
        public Grid DynamicControlsContainer {get;set;}
        public string Key { get; set; }
        public string Url { get; set; }
        public Uri Uri { get; set; }
        public Storyboard LoadingAnimation { get; set; }
        public Grid LoadingAnimationContainer { get; set; }
    }
}